import React, { useState, useEffect, useRef } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Progress } from './ui/progress';
import { Layers, Clock, Trophy, Star, Plus, Minus, ArrowUp, ArrowDown } from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';
import { TestResult } from '../types';

interface MultitaskTestProps {
  onComplete: (result: TestResult) => void;
}

interface Task {
  id: string;
  type: 'math' | 'memory' | 'reaction' | 'sequence';
  content: any;
  completed: boolean;
  score: number;
}

interface MathTask {
  question: string;
  answer: number;
  userAnswer?: number;
}

interface MemoryTask {
  sequence: number[];
  userSequence: number[];
  showSequence: boolean;
}

interface ReactionTask {
  color: string;
  targetColor: string;
  reactionTime?: number;
}

interface SequenceTask {
  pattern: string[];
  nextItem: string;
  userAnswer?: string;
  options: string[];
}

export function MultitaskTest({ onComplete }: MultitaskTestProps) {
  const [stage, setStage] = useState<'instructions' | 'test' | 'results'>('instructions');
  const [currentTasks, setCurrentTasks] = useState<Task[]>([]);
  const [activeTaskId, setActiveTaskId] = useState<string | null>(null);
  const [timeLeft, setTimeLeft] = useState(180); // 3分钟
  const [startTime, setStartTime] = useState<number>(0);
  const [totalScore, setTotalScore] = useState(0);
  const [completedTasks, setCompletedTasks] = useState(0);
  const [taskSwitches, setTaskSwitches] = useState(0);

  const intervalRef = useRef<NodeJS.Timeout>();
  const memoryTimersRef = useRef<Map<string, NodeJS.Timeout>>(new Map());

  useEffect(() => {
    if (stage === 'test' && timeLeft > 0) {
      intervalRef.current = setInterval(() => {
        setTimeLeft(prev => {
          if (prev <= 1) {
            setStage('results');
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    }

    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
    };
  }, [stage, timeLeft]);

  // Handle memory task timers
  useEffect(() => {
    currentTasks.forEach(task => {
      if (task.type === 'memory') {
        const memoryContent = task.content as MemoryTask;
        if (memoryContent.showSequence && !memoryTimersRef.current.has(task.id)) {
          const timer = setTimeout(() => {
            setCurrentTasks(prev => prev.map(t => 
              t.id === task.id 
                ? { ...t, content: { ...memoryContent, showSequence: false } }
                : t
            ));
            memoryTimersRef.current.delete(task.id);
          }, Math.max(2000, memoryContent.sequence.length * 600));
          
          memoryTimersRef.current.set(task.id, timer);
        }
      }
    });

    // Cleanup timers for removed tasks
    const currentTaskIds = new Set(currentTasks.map(t => t.id));
    memoryTimersRef.current.forEach((timer, taskId) => {
      if (!currentTaskIds.has(taskId)) {
        clearTimeout(timer);
        memoryTimersRef.current.delete(taskId);
      }
    });

    return () => {
      // Cleanup all timers on unmount
      memoryTimersRef.current.forEach(timer => clearTimeout(timer));
      memoryTimersRef.current.clear();
    };
  }, [currentTasks]);

  const generateMathTask = (): MathTask => {
    const operations = ['+', '-', '*'];
    const operation = operations[Math.floor(Math.random() * operations.length)];
    let a, b: number;
    let answer: number;
    let question: string;
    
    switch (operation) {
      case '+':
        a = Math.floor(Math.random() * 15) + 1;
        b = Math.floor(Math.random() * 15) + 1;
        answer = a + b;
        question = `${a} + ${b} = ?`;
        break;
      case '-':
        // 确保结果为正数且不太大
        a = Math.floor(Math.random() * 20) + 10;
        b = Math.floor(Math.random() * (a - 1)) + 1;
        answer = a - b;
        question = `${a} - ${b} = ?`;
        break;
      case '*':
        a = Math.floor(Math.random() * 8) + 2;
        b = Math.floor(Math.random() * 8) + 2;
        answer = a * b;
        question = `${a} × ${b} = ?`;
        break;
      default:
        a = Math.floor(Math.random() * 15) + 1;
        b = Math.floor(Math.random() * 15) + 1;
        answer = a + b;
        question = `${a} + ${b} = ?`;
    }

    return { question, answer };
  };

  const generateMemoryTask = (): MemoryTask => {
    const length = Math.floor(Math.random() * 3) + 4; // 4-6位数字
    const sequence = Array.from({ length }, () => Math.floor(Math.random() * 9) + 1);
    return {
      sequence,
      userSequence: [],
      showSequence: true
    };
  };

  const generateReactionTask = (): ReactionTask => {
    const colors = ['red', 'blue', 'green', 'yellow', 'purple', 'orange'];
    const currentColor = colors[Math.floor(Math.random() * colors.length)];
    const targetColor = colors[Math.floor(Math.random() * colors.length)];
    
    return {
      color: currentColor,
      targetColor
    };
  };

  const generateSequenceTask = (): SequenceTask => {
    const patterns = [
      { pattern: ['A', 'B', 'C'], next: 'D' },
      { pattern: ['1', '2', '3'], next: '4' },
      { pattern: ['○', '●', '○'], next: '●' },
      { pattern: ['△', '□', '△'], next: '□' }
    ];
    
    const selected = patterns[Math.floor(Math.random() * patterns.length)];
    const options = [];
    options.push(selected.next);
    
    // 添加干扰选项
    const allOptions = ['A', 'B', 'C', 'D', 'E', '1', '2', '3', '4', '5', '○', '●', '△', '□'];
    while (options.length < 4) {
      const option = allOptions[Math.floor(Math.random() * allOptions.length)];
      if (!options.includes(option)) {
        options.push(option);
      }
    }
    
    // 打乱选项
    for (let i = options.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [options[i], options[j]] = [options[j], options[i]];
    }
    
    return {
      pattern: selected.pattern,
      nextItem: selected.next,
      options
    };
  };

  const createNewTask = (): Task => {
    const types: Task['type'][] = ['math', 'memory', 'reaction', 'sequence'];
    const type = types[Math.floor(Math.random() * types.length)];
    const id = `${type}_${Date.now()}_${Math.random()}`;

    let content: any;
    switch (type) {
      case 'math':
        content = generateMathTask();
        break;
      case 'memory':
        content = generateMemoryTask();
        break;
      case 'reaction':
        content = generateReactionTask();
        break;
      case 'sequence':
        content = generateSequenceTask();
        break;
    }

    return {
      id,
      type,
      content,
      completed: false,
      score: 0
    };
  };

  const handleStartTest = () => {
    setStage('test');
    setStartTime(Date.now());
    
    // 初始化3个任务
    const initialTasks = [createNewTask(), createNewTask(), createNewTask()];
    setCurrentTasks(initialTasks);
    setActiveTaskId(initialTasks[0].id);
  };

  const handleTaskSwitch = (taskId: string) => {
    if (taskId !== activeTaskId) {
      setActiveTaskId(taskId);
      setTaskSwitches(prev => prev + 1);
    }
  };

  const handleTaskComplete = (taskId: string, score: number) => {
    // Clean up memory timer for this task
    const timer = memoryTimersRef.current.get(taskId);
    if (timer) {
      clearTimeout(timer);
      memoryTimersRef.current.delete(taskId);
    }

    setCurrentTasks(prev => prev.map(task => 
      task.id === taskId 
        ? { ...task, completed: true, score }
        : task
    ));
    
    setTotalScore(prev => prev + score);
    setCompletedTasks(prev => prev + 1);
    
    // 添加新任务替换完成的任务
    setTimeout(() => {
      const newTask = createNewTask();
      setCurrentTasks(prev => prev.map(task =>
        task.id === taskId ? newTask : task
      ));
      
      // 如果当前活跃任务完成了，切换到新任务
      if (activeTaskId === taskId) {
        setActiveTaskId(newTask.id);
      }
    }, 800); // 缩短等待时间，提高测试流畅性
  };

  const handleComplete = () => {
    const timeUsed = Math.round((Date.now() - startTime) / 1000);
    const efficiency = completedTasks > 0 ? Math.round((totalScore / completedTasks)) : 0;
    
    // 重新设计评分算法 - 更公平地评估切换策略
    const baseScore = Math.min(100, (totalScore / 5)); // 基础分数基于总得分
    const completionBonus = Math.min(20, completedTasks * 2); // 完成任务奖励
    const timeBonus = Math.max(0, (180 - timeUsed) / 18); // 时间奖励，最多10分
    
    // 重新计算切换效率 - 考虑切换与完成任务的比例
    const switchingEfficiency = completedTasks > 0 ? taskSwitches / completedTasks : 0;
    let switchingScore = 0;
    
    if (switchingEfficiency <= 1.5) {
      // 高效切换：每完成的任务切换不超过1.5次，给予奖励
      switchingScore = Math.min(15, 15 - (switchingEfficiency - 0.5) * 10);
    } else if (switchingEfficiency <= 3) {
      // 适度切换：轻微惩罚
      switchingScore = Math.max(-10, 5 - (switchingEfficiency - 1.5) * 10);
    } else {
      // 过度切换：较大惩罚
      switchingScore = Math.max(-25, -10 - (switchingEfficiency - 3) * 5);
    }
    
    const finalScore = Math.round(Math.max(0, Math.min(100, baseScore + completionBonus + timeBonus + switchingScore)));

    const result: TestResult = {
      id: Date.now().toString(),
      testType: 'multitask',
      score: finalScore,
      completedAt: new Date(),
      duration: timeUsed,
      details: {
        completedTasks,
        totalScore,
        taskSwitches,
        efficiency,
        averageScorePerTask: completedTasks > 0 ? Math.round(totalScore / completedTasks) : 0,
        baseScore: Math.round(baseScore),
        completionBonus: Math.round(completionBonus),
        timeBonus: Math.round(timeBonus),
        switchingEfficiency: Math.round(switchingEfficiency * 100) / 100,
        switchingScore: Math.round(switchingScore),
        multitaskingEfficiency: completedTasks > 0 ? Math.round((completedTasks * 60) / (timeUsed / 60)) : 0 // 每分钟完成任务数
      }
    };

    onComplete(result);
  };

  const renderMathTask = (task: Task) => {
    const mathContent = task.content as MathTask;
    
    const handleAnswerSubmit = (answer: number) => {
      const score = answer === mathContent.answer ? 10 : 0;
      handleTaskComplete(task.id, score);
    };

    // 生成包含正确答案的选项
    const generateOptions = () => {
      const correctAnswer = mathContent.answer;
      const options = new Set([correctAnswer]);
      
      // 添加干扰选项
      while (options.size < 6) {
        const distractor = correctAnswer + Math.floor(Math.random() * 10) - 5;
        if (distractor >= 0 && distractor !== correctAnswer) {
          options.add(distractor);
        }
      }
      
      return Array.from(options).sort((a, b) => a - b);
    };

    const options = generateOptions();

    return (
      <div className="space-y-4">
        <h3 className="text-lg font-semibold text-center text-slate-700">{mathContent.question}</h3>
        <div className="grid grid-cols-2 gap-2">
          {options.map((num) => (
            <Button
              key={num}
              onClick={() => handleAnswerSubmit(num)}
              className="h-10 text-sm hover:bg-teal-50 hover:border-teal-300 transition-colors"
              variant="outline"
            >
              {num}
            </Button>
          ))}
        </div>
      </div>
    );
  };

  const renderMemoryTask = (task: Task) => {
    const memoryContent = task.content as MemoryTask;

    const handleNumberClick = (num: number) => {
      const newUserSequence = [...memoryContent.userSequence, num];
      
      // 实时检查错误
      const currentIndex = newUserSequence.length - 1;
      if (newUserSequence[currentIndex] !== memoryContent.sequence[currentIndex]) {
        // 输入错误，立即完成任务，给0分
        handleTaskComplete(task.id, 0);
        return;
      }
      
      if (newUserSequence.length === memoryContent.sequence.length) {
        const score = 15; // 如果到这里说明全部正确
        handleTaskComplete(task.id, score);
      } else {
        setCurrentTasks(prev => prev.map(t =>
          t.id === task.id 
            ? { ...t, content: { ...memoryContent, userSequence: newUserSequence } }
            : t
        ));
      }
    };

    if (memoryContent.showSequence) {
      return (
        <div className="text-center space-y-4">
          <h3 className="font-semibold text-slate-700">记住这个序列</h3>
          <div className="text-2xl font-mono tracking-wider text-teal-600 font-bold">
            {memoryContent.sequence.join(' - ')}
          </div>
          <div className="text-sm text-slate-500">
            ({memoryContent.sequence.length}位数字)
          </div>
        </div>
      );
    }

    return (
      <div className="space-y-4">
        <h3 className="font-semibold text-center text-slate-700">请按顺序点击数字</h3>
        <div className="text-center text-sm text-slate-600">
          进度: {memoryContent.userSequence.length}/{memoryContent.sequence.length}
        </div>
        <div className="text-center text-xs text-teal-600 font-mono">
          已输入: {memoryContent.userSequence.join(' - ') || '(空)'}
        </div>
        <div className="grid grid-cols-3 gap-2">
          {[1,2,3,4,5,6,7,8,9].map(num => (
            <Button
              key={num}
              onClick={() => handleNumberClick(num)}
              className="h-10 text-sm hover:bg-teal-50 hover:border-teal-300 transition-colors"
              variant="outline"
            >
              {num}
            </Button>
          ))}
        </div>
      </div>
    );
  };

  const renderReactionTask = (task: Task) => {
    const reactionContent = task.content as ReactionTask;
    
    const handleColorClick = (clicked: string) => {
      const correct = clicked === reactionContent.targetColor;
      const score = correct ? 8 : 0;
      handleTaskComplete(task.id, score);
    };

    const colorMap = {
      red: { bg: 'bg-red-500', name: '红色' },
      blue: { bg: 'bg-blue-500', name: '蓝色' },
      green: { bg: 'bg-green-500', name: '绿色' },
      yellow: { bg: 'bg-yellow-500', name: '黄色' },
      purple: { bg: 'bg-purple-500', name: '紫色' },
      orange: { bg: 'bg-orange-500', name: '橙色' }
    };

    const targetColorName = colorMap[reactionContent.targetColor as keyof typeof colorMap]?.name || reactionContent.targetColor;

    return (
      <div className="space-y-4">
        <h3 className="font-semibold text-center text-slate-700">
          点击：<span className="text-lg font-bold text-teal-600">{targetColorName}</span>
        </h3>
        <div className="grid grid-cols-3 gap-2">
          {Object.entries(colorMap).map(([color, { bg }]) => (
            <button
              key={color}
              onClick={() => handleColorClick(color)}
              className={`w-full h-12 rounded-lg ${bg} hover:opacity-80 hover:scale-105 transition-all duration-200 shadow-sm border border-white/20`}
              title={colorMap[color as keyof typeof colorMap].name}
            />
          ))}
        </div>
      </div>
    );
  };

  const renderSequenceTask = (task: Task) => {
    const sequenceContent = task.content as SequenceTask;
    
    const handleAnswerClick = (answer: string) => {
      const correct = answer === sequenceContent.nextItem;
      const score = correct ? 12 : 0;
      handleTaskComplete(task.id, score);
    };

    return (
      <div className="space-y-4">
        <h3 className="font-semibold text-center">找出下一项</h3>
        <div className="text-center text-lg">
          {sequenceContent.pattern.join(' → ')} → ?
        </div>
        <div className="grid grid-cols-2 gap-2">
          {sequenceContent.options.map((option, index) => (
            <Button
              key={index}
              onClick={() => handleAnswerClick(option)}
              className="h-10"
              variant="outline"
            >
              {option}
            </Button>
          ))}
        </div>
      </div>
    );
  };

  const renderTask = (task: Task) => {
    switch (task.type) {
      case 'math':
        return renderMathTask(task);
      case 'memory':
        return renderMemoryTask(task);
      case 'reaction':
        return renderReactionTask(task);
      case 'sequence':
        return renderSequenceTask(task);
      default:
        return null;
    }
  };

  if (stage === 'instructions') {
    return (
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-teal-200 shadow-lg">
          <CardHeader className="text-center pb-8">
            <div className="w-16 h-16 bg-gradient-to-br from-teal-500 to-cyan-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
              <Layers className="w-8 h-8 text-white" />
            </div>
            <CardTitle className="text-2xl text-slate-800">多任务处理测试</CardTitle>
            <p className="text-slate-600 mt-2">测试您同时处理多个任务的执行能力</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="bg-gradient-to-r from-teal-50 to-cyan-50 rounded-xl p-6 border border-teal-100">
              <h3 className="font-semibold text-teal-900 mb-4 flex items-center gap-2">
                <Star className="w-5 h-5" />
                测试说明
              </h3>
              <div className="space-y-3 text-slate-700">
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-teal-500 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">1</span>
                  <p>您将同时面对3个不同类型的任务窗口</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-teal-500 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">2</span>
                  <p>任务包括数学计算、记忆序列、颜色反应和模式识别</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-teal-500 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">3</span>
                  <p>在不同任务之间切换完成，完成的任务会自动替换为新任务</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-teal-500 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">4</span>
                  <p>战略性任务切换比无目的频繁跳跃更高效</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-teal-500 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">5</span>
                  <p>建议：当任务卡住或等待时再切换到其他任务</p>
                </div>
              </div>
            </div>

            <div className="bg-gradient-to-r from-orange-50 to-yellow-50 rounded-xl p-6 border border-orange-100">
              <h3 className="font-semibold text-orange-900 mb-4 flex items-center gap-2">
                <Star className="w-5 h-5" />
                切换策略提示
              </h3>
              <div className="space-y-2 text-slate-700">
                <p>• <span className="font-semibold">高效策略</span>：当记忆任务正在显示序列时，切换去完成其他任务</p>
                <p>• <span className="font-semibold">避免无效切换</span>：不要在能立即完成的任务上频繁跳跃</p>
                <p>• <span className="font-semibold">合理利用等待</span>：利用任务间的自然间隙进行切换</p>
              </div>
            </div>

            <div className="grid md:grid-cols-3 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-teal-50 to-teal-100 rounded-xl border border-teal-200">
                <div className="text-2xl font-bold text-teal-600 mb-1">3</div>
                <div className="text-sm text-teal-700">分钟限时</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-cyan-50 to-cyan-100 rounded-xl border border-cyan-200">
                <div className="text-2xl font-bold text-cyan-600 mb-1">4</div>
                <div className="text-sm text-cyan-700">任务类型</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-teal-50 to-cyan-50 rounded-xl border border-teal-200">
                <div className="text-2xl font-bold text-slate-600 mb-1">∞</div>
                <div className="text-sm text-slate-700">任务数量</div>
              </div>
            </div>

            <Button 
              onClick={handleStartTest}
              className="w-full bg-gradient-to-r from-teal-500 to-cyan-500 hover:from-teal-600 hover:to-cyan-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              开始测试
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'test') {
    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-6xl mx-auto space-y-6"
      >
        {/* 顶部状态栏 */}
        <div className="flex flex-col sm:flex-row gap-4 items-center justify-between bg-white/80 backdrop-blur-sm rounded-lg p-4 border border-teal-200">
          <div className="flex items-center gap-6">
            <Badge variant="outline" className="bg-teal-100 text-teal-700 border-teal-300">
              已完成: {completedTasks}
            </Badge>
            <div className="flex items-center gap-2 text-slate-600">
              <Trophy className="w-4 h-4" />
              <span className="font-semibold">{totalScore} 分</span>
            </div>
            <Badge variant="outline" className="bg-slate-100 text-slate-700 border-slate-300">
              切换: {taskSwitches}次
            </Badge>
          </div>
          
          <div className="flex items-center gap-2">
            <Clock className="w-4 h-4 text-slate-500" />
            <span className={`font-mono text-lg font-bold ${timeLeft <= 30 ? 'text-red-500' : 'text-slate-700'}`}>
              {Math.floor(timeLeft / 60)}:{(timeLeft % 60).toString().padStart(2, '0')}
            </span>
          </div>
        </div>

        {/* 任务网格 */}
        <div className="grid md:grid-cols-3 gap-6">
          {currentTasks.map((task, index) => {
            const isActive = task.id === activeTaskId;
            const taskTypeNames = {
              math: '数学计算',
              memory: '记忆序列',
              reaction: '颜色反应',
              sequence: '模式识别'
            };
            
            return (
              <motion.div
                key={task.id}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: index * 0.1 }}
              >
                <Card 
                  className={`cursor-pointer transition-all duration-300 ${
                    isActive 
                      ? 'bg-gradient-to-br from-teal-50 to-cyan-50 border-teal-300 shadow-lg scale-105' 
                      : 'bg-white/80 border-slate-200 hover:border-teal-200'
                  } ${task.completed ? 'opacity-50' : ''}`}
                  onClick={() => handleTaskSwitch(task.id)}
                >
                  <CardHeader className="pb-3">
                    <CardTitle className="text-sm font-semibold flex items-center justify-between">
                      <span>{taskTypeNames[task.type]}</span>
                      <Badge variant="outline" className={`text-xs ${
                        isActive 
                          ? 'bg-teal-100 text-teal-700 border-teal-300' 
                          : 'bg-slate-100 text-slate-600 border-slate-200'
                      }`}>
                        {isActive ? '活跃' : '等待'}
                      </Badge>
                    </CardTitle>
                  </CardHeader>
                  
                  <CardContent className="pt-0">
                    <AnimatePresence mode="wait">
                      {task.completed ? (
                        <motion.div
                          initial={{ opacity: 0 }}
                          animate={{ opacity: 1 }}
                          className="text-center py-8 text-green-600"
                        >
                          <Trophy className="w-8 h-8 mx-auto mb-2" />
                          <p className="font-semibold">已完成</p>
                          <p className="text-xs">+{task.score}分</p>
                        </motion.div>
                      ) : (
                        <motion.div
                          initial={{ opacity: 0 }}
                          animate={{ opacity: 1 }}
                          className={`${isActive ? '' : 'opacity-50'}`}
                        >
                          {renderTask(task)}
                        </motion.div>
                      )}
                    </AnimatePresence>
                  </CardContent>
                </Card>
              </motion.div>
            );
          })}
        </div>
      </motion.div>
    );
  }

  if (stage === 'results') {
    const timeUsed = Math.round((Date.now() - startTime) / 1000);
    const efficiency = completedTasks > 0 ? Math.round((totalScore / completedTasks)) : 0;
    
    // 重新计算评分指标 - 与handleComplete保持一致
    const baseScore = Math.min(100, (totalScore / 5));
    const completionBonus = Math.min(20, completedTasks * 2);
    const timeBonus = Math.max(0, (180 - timeUsed) / 18);
    
    const switchingEfficiency = completedTasks > 0 ? taskSwitches / completedTasks : 0;
    let switchingScore = 0;
    
    if (switchingEfficiency <= 1.5) {
      switchingScore = Math.min(15, 15 - (switchingEfficiency - 0.5) * 10);
    } else if (switchingEfficiency <= 3) {
      switchingScore = Math.max(-10, 5 - (switchingEfficiency - 1.5) * 10);
    } else {
      switchingScore = Math.max(-25, -10 - (switchingEfficiency - 3) * 5);
    }
    
    const finalScore = Math.round(Math.max(0, Math.min(100, baseScore + completionBonus + timeBonus + switchingScore)));
    const multitaskingEfficiency = completedTasks > 0 ? Math.round((completedTasks * 60) / (timeUsed / 60)) : 0;

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-teal-200 shadow-xl">
          <CardHeader className="text-center pb-6">
            <motion.div
              initial={{ scale: 0 }}
              animate={{ scale: 1 }}
              transition={{ delay: 0.2, type: "spring", stiffness: 200 }}
              className="w-20 h-20 bg-gradient-to-br from-teal-500 to-cyan-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
            >
              <Trophy className="w-10 h-10 text-white" />
            </motion.div>
            
            <CardTitle className="text-3xl text-slate-800 mb-2">测试完成！</CardTitle>
            <div className="text-6xl font-bold bg-gradient-to-r from-teal-500 to-cyan-500 bg-clip-text text-transparent">
              {finalScore}
            </div>
            <p className="text-slate-600">多任务处理能力得分</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="grid grid-cols-2 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-teal-50 to-teal-100 rounded-xl border border-teal-200">
                <div className="text-2xl font-bold text-teal-600 mb-1">{completedTasks}</div>
                <div className="text-sm text-teal-700">完成任务</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-cyan-50 to-cyan-100 rounded-xl border border-cyan-200">
                <div className="text-2xl font-bold text-cyan-600 mb-1">{totalScore}</div>
                <div className="text-sm text-cyan-700">总得分</div>
              </div>
            </div>

            <div className="space-y-3">
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">任务效率</span>
                <span className="font-semibold text-slate-800">{efficiency}分/任务</span>
              </div>
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">多任务效率</span>
                <span className="font-semibold text-slate-800">{multitaskingEfficiency}任务/分钟</span>
              </div>
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">切换次数</span>
                <span className="font-semibold text-slate-800">{taskSwitches}次</span>
              </div>
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">切换效率</span>
                <span className="font-semibold text-slate-800">{Math.round(switchingEfficiency * 100) / 100}次/任务</span>
              </div>
            </div>

            <div className="bg-gradient-to-r from-teal-50 to-cyan-50 rounded-lg p-4 border border-teal-200">
              <h4 className="font-semibold text-teal-800 mb-2">得分构成</h4>
              <div className="space-y-1 text-sm">
                <div className="flex justify-between">
                  <span className="text-slate-600">基础分数</span>
                  <span className="text-slate-800">{Math.round(baseScore)}分</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-slate-600">完成奖励</span>
                  <span className="text-green-600">+{Math.round(completionBonus)}分</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-slate-600">时间奖励</span>
                  <span className="text-blue-600">+{Math.round(timeBonus)}分</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-slate-600">切换策略</span>
                  <span className={`${switchingScore >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                    {switchingScore >= 0 ? '+' : ''}{Math.round(switchingScore)}分
                  </span>
                </div>
              </div>
            </div>

            <Button 
              onClick={handleComplete}
              className="w-full bg-gradient-to-r from-teal-500 to-cyan-500 hover:from-teal-600 hover:to-cyan-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              查看详细结果
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  return null;
}